package com.yun.zf.system.security.filter;

import cn.hutool.core.io.IoUtil;
import com.alibaba.fastjson.JSONObject;
import com.yun.zf.common.app.model.wechat.WeChatUserInfoMo;
import com.yun.zf.system.exception.BaseException;
import com.yun.zf.system.exception.CustomException;
import com.yun.zf.system.security.token.WxAppletAuthenticationToken;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter;
import org.springframework.web.servlet.HandlerExceptionResolver;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;

/**
 * 自定义微信登录拦截器
 */

@Slf4j
public class WxAppletAuthenticationFilter extends AbstractAuthenticationProcessingFilter {

    public WxAppletAuthenticationFilter() {
        super("/wechatLogin");
    }

    @Autowired
    @Qualifier("handlerExceptionResolver")
    private HandlerExceptionResolver resolver;

    @Override
    public Authentication attemptAuthentication(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws BaseException  {

        //如果是json请求使用取参数逻辑
        WeChatUserInfoMo weChatUserInfoMo = null;
        try (InputStream is = httpServletRequest.getInputStream()) {
            String params = IoUtil.read(is,"UTF-8");
            if (StringUtils.isNotBlank(params)){
                weChatUserInfoMo = JSONObject.parseObject(params,WeChatUserInfoMo.class);
            }
        } catch (IOException e) {
            resolver.resolveException(httpServletRequest,httpServletResponse,null,new CustomException("参数错误----"));
            return null;
        }
        if(StringUtils.isBlank(weChatUserInfoMo.getCode())){
            resolver.resolveException(httpServletRequest,httpServletResponse,null,new CustomException("code不允许为空"));
            return null;
        }

        // 将信息放入token中以便在provider中获取
        WxAppletAuthenticationToken wxAppletAuthenticationToken =    new WxAppletAuthenticationToken(weChatUserInfoMo);
       return this.getAuthenticationManager().authenticate(wxAppletAuthenticationToken);

    }



}